const cheerio = require('cheerio');
const _ = require('underscore');
const Base = require('./_base')
const path = window.require('path');
const md5 = require('js-md5');

export default class Gather extends Base{
	constructor(reportCb) {
	    super(reportCb);
	    this.enterurl = 'http://www.bonaldo.it/it/prodotti?search_api_views_fulltext='
	    this.host='http://www.bonaldo.it';
      this.pathname = path.resolve('data/' + md5(this.enterurl))
	  }
	  getProductUrls = async() => {
	  	let res = await fetch(this.enterurl).then(res => res.text());
	  	 let $ = cheerio.load(res)
     	var html=$('.view-content').eq(0).html();
     	var arr=[];
 		var res1=$('.views-row',html).each(function(i,el){
 		var html2=$('.field-content',$(this).html()).html();
 		var add = $('a',html2).attr('href');
 			arr.push(add);
 		});
 		for (let i of _.range(arr.slice(0,4).length)) {
 		  let url = arr[i]
 		  this.status.msg = '获取列表'
 		  this.status.current = i + 1
 		  this.status.count = arr.length
 		  this.reportCb(this.status)
 		}
 		return arr;
	  }
	  getProduct = async(url) => {
	  	let res = await fetch(this.host+url).then(res => res.text());
	  	let $ = cheerio.load(res)
		let product={};
		if($('#flexslider-4').html()!==null){
			let imgs=[];
			if($('#flexslider-4 ul.slides li')===undefined)return false;
			$('#flexslider-4 ul.slides li').each(function(j,ele){
				imgs.push($('img',$(this).html()).attr('src'))
			});
			//获取商品的详细信息
			// product.origin_html=$('html').html();
			product.origin_url = this.host+url;
			product.brand_num='bonaldo';
			product.images=[];
			product.path=[];
			product.local_path=[];
			let info=$('#node_product_full_group_product_description').html();
			if($('.field-items',info)===undefined||$('.field-items',info).length<1)return false;
			$('.field-items',info).each(function(k,ele){
				k==0?product.name=$(this).text():'';
				k==1?product.design=$(this).text():'';
				k==2?product.infos=$(this).text():'';
				k==3?product.description=$(this).text():'';

			});
			for(var key of imgs){
					if(key.split('?').length>1){
						key=key.split('?')[0];
					}
					product.images.push({"pic_url":key});
			}
		}
		if(Object.keys(product).length>1){
			return product
		}
	  }
}
